package org.lookahead.parent.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import io.swagger.v3.oas.annotations.Operation;

public class JacksonXmlUtil {

    @Operation(summary = "xml字符串转json字符串")
    public static String xmlToJson(String xml, Boolean hasRoot) {
        XmlMapper mapper = new XmlMapper();
        String content;
        if (hasRoot) {
            content = xml;
        } else {
            content = "<root>" + xml + "</root>";
        }
        try {
            // 将XML转换为JsonNode对象
            return mapper.readTree(content).toString();
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) {
        String xml =
                "<describe>Read and understand.</describe>" +
                "<text>Mr Green is a sports reporter. He often watches football games. " +
                "He writes reports on football games. He also writes reports on football players. " +
                "He reads a lot about football players, too. He knows a lot about football stars.\\n" +
                "He often goes to other countries towatch football games. " +
                "He always takes a computer and a camera(相机) with him. " +
                "He does not have an office. He works on airplane, in a gym or in a hotel.\\n" +
                "But he does not play football. He does Chinese kung fu and goes swimming to stay healthy.\\n" +
                "Mr Green loves his work.\\n</text>" +
                "<image>image/202401/597c4e874ecc578b5abcfa3f73be4c8d.png</image>" +
                "<audio></audio>";
        String xml1 = "<text startTime=\"00:09.20\" endTime=\"00:13.10\" audioUrl=\"undefined\" >Good morning. Welcome to school.</text>";
        System.out.println("JSON:\n" + JacksonXmlUtil.xmlToJson(xml, false));
        System.out.println("JSON:\n" + JacksonXmlUtil.xmlToJson(xml1, false));
    }
}
